package com.ruoyi.eqmonitor.controller;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.eqmonitor.domain.OptDeviceAlarm;
import com.ruoyi.eqmonitor.dtos.*;
import com.ruoyi.eqmonitor.service.IOptDeviceAlarmService;
import com.ruoyi.eqmonitor.utils.Constant;
import com.ruoyi.eqmonitor.vo.BszsVo;
import com.ruoyi.eqmonitor.vo.CsyzVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;

import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.utils.poi.ExcelUtil;

import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 设备预警
 *
 * @author ruoyi
 * @date 2022-11-25
 */
@RestController
@RequestMapping("/alarm")
public class OptDeviceAlarmController extends BaseController {

    @Autowired
    private IOptDeviceAlarmService optDeviceAlarmService;

    @GetMapping("/list")
    public TableDataInfo<?> list(AlarmSearchInput optDeviceAlarm) {
        startPage();
        return getDataTable(optDeviceAlarmService.selectOptDeviceAlarmList(optDeviceAlarm));
    }

    /**
     * 根据报警现象获取所有报警记录的位置
     */
    @GetMapping("/clog/getAlarmPosition")
    public AjaxResult getAlarmPosition() {
        // 只查询 管网淤堵, 管网满管
        LambdaQueryWrapper<OptDeviceAlarm> wrapper = Wrappers.lambdaQuery();
        wrapper.select(OptDeviceAlarm::getId,
                OptDeviceAlarm::getAlarmPhenomenon,
                OptDeviceAlarm::getAbx,
                OptDeviceAlarm::getAby,
                OptDeviceAlarm::getDeviceCode,
                OptDeviceAlarm::getDeviceName
        );
        wrapper.in(OptDeviceAlarm::getAlarmPhenomenon,
                ListUtil.of(
                        Constant.AlarmPhenomenon.CLOGGING.getValue(),
                        Constant.AlarmPhenomenon.FULL_PACKAGE.getValue()
                )
        );
        // 只查询持续报警的内容
        wrapper.eq(OptDeviceAlarm::getPersistentStatus, Constant.TRUE);
//        wrapper.groupBy(OptDeviceAlarm::getDeviceCode);
        return success(optDeviceAlarmService.listMaps(wrapper));
    }

    /**
     * 报警记录列表及处置详情
     *
     * @param optDeviceAlarm 报警记录查询条件
     * @return 报警记录列表及处置详情
     */
    @GetMapping("/listAndDispatch")
    public TableDataInfo<?> listAndDispatch(AlarmSearchInput optDeviceAlarm) {
        // menuType 0 超阈值  1离线+超上限
        startPage();
        return getDataTable(optDeviceAlarmService.listAndDispatch(optDeviceAlarm));
    }
    @GetMapping("/listAndDispatchWithOutJg")
    public TableDataInfo<?> listAndDispatchWithOutJg(AlarmSearchInput optDeviceAlarm) {
        startPage();
        if(optDeviceAlarm.getStartTime() == null){
            LocalDateTime startTime = LocalDateTime.now().minusDays(2);
            optDeviceAlarm.setStartTime(Date.from(startTime.atZone( ZoneId.systemDefault()).toInstant()));
            optDeviceAlarm.setEndTime(Date.from(LocalDateTime.now().atZone( ZoneId.systemDefault()).toInstant()));
            optDeviceAlarm.setPersistentStatus(0);
        }
        optDeviceAlarm.setDeviceTypeExclude("SJ500-L-Y0");
        optDeviceAlarm.setPersistentStatus(0);
        //屏蔽离线
        //optDeviceAlarm.setAlarmTypeExclude(10);
        logger.info("optDeviceAlarm2:{}", JSONObject.toJSONString(optDeviceAlarm));
        return getDataTable(optDeviceAlarmService.listAndDispatch(optDeviceAlarm));
    }
    /**
     * 运维管理使用 -- 按时间周期搜索分页
     *
     * @param optDeviceAlarm 报警记录查询条件
     * @return 报警记录列表及处置详情
     */
    @GetMapping("/deviceListAndDispatch")
    public TableDataInfo<?> deviceListAndDispatch(AlarmSearchInput optDeviceAlarm) {
        startPage();
        return getDataTable(optDeviceAlarmService.deviceListAndDispatch(optDeviceAlarm));
    }

    /**
     * 查询设备报警类表
     */
    @GetMapping("/clog/list")
    public TableDataInfo<?> listClog(OptDeviceAlarmDto dto) {
        startPage();
        if (CollectionUtil.isEmpty(dto.getAlarmPhenomenons()) && StrUtil.isEmpty(dto.getAlarmPhenomenon())) {
            // 只查询 管网淤堵, 管网满管
            dto.setAlarmPhenomenons(ListUtil.of(
                    Constant.AlarmPhenomenon.CLOGGING.getValue(),
                    Constant.AlarmPhenomenon.FULL_PACKAGE.getValue()
            ));
        }
        List<OptDeviceAlarmDto> list = optDeviceAlarmService.selectOptDeviceAlarmClogList(dto);
        return getDataTable(list);
    }

    /**
     * 获取泵站报警列表
     */
    @ApiOperation("获取泵站报警列表")
    @GetMapping("/station/list")
    public TableDataInfo<?> listStation(OptDeviceAlarmDto dto) {
        startPage();
        if (CollectionUtil.isEmpty(dto.getAlarmPhenomenons()) && StrUtil.isEmpty(dto.getAlarmPhenomenon())) {
            // 只查询 COD越界, 氨氮越界, 入流入渗
            dto.setAlarmPhenomenons(
                    ListUtil.of(
                            Constant.AlarmPhenomenon.COD_OVERSTEP.getValue(),
                            Constant.AlarmPhenomenon.AMMONIA_NITROGEN_OVERSTEP.getValue(),
                            Constant.AlarmPhenomenon.INFLOW_INFILTRATION.getValue()
                    )
            );
        }
        List<OptDeviceAlarmDto> list = optDeviceAlarmService.selectOptDeviceAlarmClogList(dto);
        return getDataTable(list);
    }

    /**
     * 根据id查询报警详情
     *
     * @param id 主键
     * @return 报警详情
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(optDeviceAlarmService.selectOptDeviceAlarmById(id));
    }

    /**
     * 新增设备预警
     *
     * @param optDeviceAlarm 设备预警
     * @return 结果
     */
    @Log(title = "添加设备预警", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OptDeviceAlarm optDeviceAlarm) {
//    	optDeviceAlarm.setCreateTime(new Date());
//    	optDeviceAlarm.setCreateBy(SecurityUtils.getUsername());
        return toAjax(optDeviceAlarmService.save(optDeviceAlarm));
    }

    /**
     * 修改设备预警
     *
     * @param optDeviceAlarm 设备预警
     * @return 结果
     */
    @PutMapping
    public AjaxResult edit(@RequestBody OptDeviceAlarm optDeviceAlarm) {
//    	optDeviceAlarm.setUpdateTime(new Date());
//    	optDeviceAlarm.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(optDeviceAlarmService.updateById(optDeviceAlarm));
    }

    /**
     * 删除设备预警 传入@PathVariable的格式类似为/1,2,3,4,5时,会自动转为数组
     */
    @Log(title = "删除设备预警", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(optDeviceAlarmService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 导出设备预警列表
     */
    @Log(title = "导出设备预警", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AlarmSearchInput optDeviceAlarm) {
        List<OptDeviceAlarmDto> list = optDeviceAlarmService.listAndDispatch(optDeviceAlarm);
        ExcelUtil<OptDeviceAlarmDto> util = new ExcelUtil<OptDeviceAlarmDto>(OptDeviceAlarmDto.class);
        util.exportExcel(response, list, "导出设备预警");
    }

    /**
     * 查询各个报警数量的统计
     */
    @GetMapping("/clog/quantityStatistics")
    public AjaxResult quantityStatistics(OptDeviceAlarmDto dto) {
        return success(optDeviceAlarmService.quantityStatistics(dto));
    }

    /**
     * 查询淤堵预警详情
     */
    @GetMapping("/clog/info/{id}")
    public AjaxResult listClog(@PathVariable("id") Long id) {
        return success(optDeviceAlarmService.selectOptDeviceAlarmClogInfo(id));
    }

    /**
     * 查询报警信息，state为0查询当天,当天没有数据查询前一天，state为1查询最近三天
     *
     * @param dto
     * @return
     */
    @GetMapping("/newestList")
    public TableDataInfo<?> newestList(AlarmSearchInput dto) throws ParseException {
        return getDataTable(optDeviceAlarmService.newestList(dto));
    }

    /**
     * 畅水因子
     */
    @ApiOperation("畅水因子")
    @GetMapping("/csyzBackstage")
    public AjaxResult selectCsyzBackstage(CsyzVo query) {
        return success(optDeviceAlarmService.selectCsyzBackstage(query));
    }

    /**
     * 畅水因子-导出
     */
    @ApiOperation("畅水因子-导出")
    @Log(title = "畅水因子-导出", businessType = BusinessType.EXPORT)
    @PostMapping("/csyzBackstage/export")
    public void CSYZExport(HttpServletResponse response, CsyzVo query) {
        List<CsyzVo> list = optDeviceAlarmService.selectCsyzBackstage(query);
        ExcelUtil<CsyzVo> util = new ExcelUtil<CsyzVo>(CsyzVo.class);
        util.exportExcel(response, list, "畅水因子-导出");
    }

    /**
     * 碧水指数
     */
    @ApiOperation("碧水指数")
    @GetMapping("/bszsBackstage")
    public AjaxResult selectBSZSBackstage(BszsVo query) {
        return success(optDeviceAlarmService.selectBSZSBackstage(query));
    }

    /**
     * 碧水指数-导出
     */
    @ApiOperation("碧水指数-导出")
    @Log(title = "碧水指数-导出", businessType = BusinessType.EXPORT)
    @PostMapping("/bszsBackstage/export")
    public void BSZSExport(HttpServletResponse response, BszsVo query) {
        List<BszsVo> list = optDeviceAlarmService.selectBSZSBackstage(query);
        ExcelUtil<BszsVo> util = new ExcelUtil<BszsVo>(BszsVo.class);
        util.exportExcel(response, list, "碧水指数-导出");
    }

    /**
     * 碧水指数和畅水因子模块的报警设备详情
     */
    @ApiOperation("碧水指数-畅水因子-报警设备详情")
    @GetMapping("/backstageDeviceCall/{state}")
    public AjaxResult backstageDeviceCall(@PathVariable("state") Integer state, BszsVo query) {
        return success(optDeviceAlarmService.backstageDeviceCall(state, query));
    }

    /**
     * 液位+水质报警
     */
    @ApiOperation("液位+水质报警")
    @GetMapping("/ywszbj")
    public AjaxResult selectYWSZBJ() {
        return success(optDeviceAlarmService.selectYWSZBJ());
    }

    /**
     * 河道报警数据
     */
    @ApiOperation("河道报警数据")
    @GetMapping("/selectRiverwayAlarm")
    public AjaxResult selectRiverwayAlarm(RiverwayAlarmDto dto) {
        return AjaxResult.success(optDeviceAlarmService.selectRiverwayAlarm(dto));
    }

}
